﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace SMP.Client.Form
{
    using DevExpress.XtraGrid.Views.Grid;
    using System.Collections;
    using SMP.Windows;
    using SMP.Service;
    using SMP.Domain;

    public partial class FrmXuatkho : SMP.Windows.Forms.FrmBase
    {
        Xuathang_Service _objXuathang = new Xuathang_Service();
        Nhaphang_Service _objNhaphang = new Nhaphang_Service();
        Phieuxuat phieuxuat = new Phieuxuat();
        DataTable dtb_phieuxuat = new DataTable();
        DataTable dtb_nha_cungcap = new DataTable();
        DataTable dtb_kho = new DataTable();
        DataTable dtb_mathang = new DataTable();
        object identity;
        public FrmXuatkho()
        {
            InitializeComponent();            
            item_Select.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            item_Print.Caption = "In hóa đơn";
        }

        #region DisplayInfo, ResetText, ChangeStatus, ClearDataBindings, DataBindingControl

        public override void DisplayInfo()
        {
            try
            {
                this.FormState = Windows.Forms.FormState.View;
                var dtb = GetSchema_DataTable_Hinhthuc_Thanhtoan();
                lookHinhthuc_Thanhtoan.Properties.DataSource = dtb;
                lookHinhthuc_Thanhtoan.ItemIndex = 0;

                dtb_nha_cungcap = _objNhaphang.GetAll_Nha_Cungcap();
                lookNha_Cungcap.Properties.DataSource = dtb_nha_cungcap;

                dtb_kho = _objNhaphang.GetAll_Kho();
                dgKho.DataSource = dtb_kho;

                dtb_phieuxuat = _objXuathang.GetAll_Phieuxuat();
                dgPhieuxuat.DataSource = dtb_phieuxuat;

                ClearDataBindings();
                ResetText();
                ChangeStatus(true);

                txtSotien_Thanhtoan.Properties.ReadOnly = true;
            }
            catch (Exception ex)
            {
                Windows.Forms.Message.Show(ex.Message, ex.ToString());
            }
        }

        public override void ResetText()
        {
            //lookHinhthuc_Thanhtoan.ResetText();
            lookNha_Cungcap.EditValue = null;
            txtTongtien.EditValue = null;
            dtNgayxuat.EditValue = DateTime.Now;

            txtSotien_Thanhtoan.EditValue = null;
            txtSotien_Conlai.EditValue = null;
            txtGhichu.EditValue = null;

            dgMathang.DataSource = null;

            lookHinhthuc_Thanhtoan.Focus();
        }

        public override void ChangeStatus(bool editTable = true)
        {
            lookHinhthuc_Thanhtoan.Properties.ReadOnly = editTable;
            lookNha_Cungcap.Properties.ReadOnly = editTable;
            txtGhichu.Properties.ReadOnly = editTable;
            txtSotien_Thanhtoan.Properties.ReadOnly = editTable;
            btnChon_Mathang.Enabled = !editTable;
            btnXoa_Mathang.Enabled = !editTable;
            gvMathang.OptionsBehavior.Editable = !editTable;
        }

        public override void ClearDataBindings()
        {
            lookHinhthuc_Thanhtoan.DataBindings.Clear();
            dtNgayxuat.DataBindings.Clear();
            txtSotien_Thanhtoan.DataBindings.Clear();
            txtSotien_Conlai.DataBindings.Clear();
            lookNha_Cungcap.DataBindings.Clear();
            txtTongtien.DataBindings.Clear();
            txtGhichu.DataBindings.Clear();
        }

        public override void DataBindingControl()
        {            
            lookHinhthuc_Thanhtoan.DataBindings.Add("EditValue", dtb_phieuxuat, ".Id_Hinhthuc_Xuathang");            
            dtNgayxuat.DataBindings.Add("EditValue", dtb_phieuxuat, ".Ngayxuat");            
            if (Convert.ToInt32("0" + lookHinhthuc_Thanhtoan.EditValue) == 1)
            {
                txtSotien_Thanhtoan.DataBindings.Add("EditValue", dtb_phieuxuat, ".Sotien_Thanhtoan");
                txtSotien_Conlai.DataBindings.Add("EditValue", dtb_phieuxuat, ".Sotien_Conlai");
            }
            lookNha_Cungcap.DataBindings.Add("EditValue", dtb_phieuxuat, ".Id_Nha_Cungcap");
            txtTongtien.DataBindings.Add("EditValue", dtb_phieuxuat, ".Tongtien");
            txtGhichu.DataBindings.Add("EditValue", dtb_phieuxuat, ".Ghichu");
        }

        #endregion


        #region PerformAdd, PerformEdit, PerformDelete, PerformCancel, PerformSave

        public override bool PerformAdd()
        {
            ClearDataBindings();
            ResetText();
            ChangeStatus(false);
            dtb_mathang = GetSchema_DataTable_Mathang();

            return true;
        }

        public override bool PerformEdit()
        {
            ChangeStatus(false);
            return true;
        }

        public override bool PerformDelete()
        {
            var del = false;
            if (Windows.Forms.Message.Show("Xóa phiếu nhập hàng có thể làm mất dữ liệu. ", "Thông Báo", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                del = _objXuathang.Delete_Phieuxuat(gvPhieuxuat.GetFocusedRowCellValue("Id_Phieuxuat"));
            if (del)
                DisplayInfo();
            return true;
        }

        public override bool PerformCancel()
        {
            ClearDataBindings();
            DisplayInfo();
            return true;
        }

        public override bool PerformSave()
        {
            var save = false;
            Hashtable hashtableControl = new Hashtable();
            hashtableControl.Add(lookHinhthuc_Thanhtoan, lbTongtien);
            hashtableControl.Add(txtTongtien, lbTongtien);
            hashtableControl.Add(lookNha_Cungcap, lbHinhthuc_Thanhtoan);
            if (lookHinhthuc_Thanhtoan.EditValue + "" == "1")
            {
                hashtableControl.Add(txtSotien_Thanhtoan, lbSotien_Thanhtoan);
                hashtableControl.Add(txtSotien_Conlai, lbSotien_Conlai);
            }
            if (!Windows.Utility.Validator.CheckNullFields(hashtableControl))
                return false;

            
            if (gvMathang.RowCount == 0)
            {
                Windows.Forms.Message.Show("Vui lòng chọn mặt hàng cần xuất", "Thông Báo");
                return false;
            }

            if (Convert.ToDecimal("0" + txtTongtien.EditValue) < (Convert.ToDecimal("0" + txtSotien_Thanhtoan.EditValue) + Convert.ToDecimal("0" + txtSotien_Conlai.EditValue)))
            {
                Windows.Forms.Message.Show("Số tiền thanh toán không được lớn hơn tổng tiền", "Thông Báo");
                return false;
            }

            foreach (DataRow dr in dtb_mathang.Rows)
            {
                if (dr["Soluong"] + "" == "" || dr["Dongia"] + "" == "")
                {
                    Windows.Forms.Message.Show("Vui lòng nhập số lượng và đơn giá đầy đủ cho từng mặt hàng", "Thông Báo");
                    gvMathang.FocusedRowHandle = gvMathang.LocateByValue(0, gvMathang.Columns["Id_Mathang"], dr["Id_Mathang"]);
                    return false;
                }

                DataRow[] row = dtb_kho.Select(string.Format("Id_Mathang = {0}", dr["Id_Mathang"]));
                if (row.Length > 0)
                {
                    if (Convert.ToDecimal("0" + row[0]["Soluong"]) < Convert.ToDecimal("0" + dr["Soluong"]) && Convert.ToDecimal("0" + dr["Soluong"]) > Convert.ToDecimal("0" + dr["Soluong_Bandau"]))
                    {
                        Windows.Forms.Message.Show("Số lượng mặt hàng lớn hơn số lượng trong kho", "Thông Báo");
                        gvMathang.FocusedRowHandle = gvMathang.LocateByValue(0, gvMathang.Columns["Id_Mathang"], dr["Id_Mathang"]);
                        return false;
                    }
                }
            }

            if (this.FormState == Windows.Forms.FormState.Add)
                save = InsertObject();
            else
                save = UpdateObject();
            if (save)
                DisplayInfo();
            gvPhieuxuat.FocusedRowHandle = gvPhieuxuat.LocateByValue(0, gvPhieuxuat.Columns["Id_Phieuxuat"], identity);

            return true;
        }

        public override bool PerformPrintPreview()
        {
            if (gvPhieuxuat.GetFocusedRowCellValue("Id_Phieuxuat") + "" == "")
            {
                Windows.Forms.Message.Show("Vui lòng chọn phiếu xuất cần in", "Thông Báo");
                return false;
            }

            var frm = new Reports.FrmRpt();
            frm.Text = "HÓA ĐƠN BÁN HÀNG";
            var rpt = new Reports.XR_Xuathang();
            
            //fill data report
            rpt.DataSource = dtb_mathang;
            rpt.Parameters["paraTen_Nha_Cungcap"].Value = lookNha_Cungcap.Text;
            rpt.Parameters["paraNgayxuat"].Value = dtNgayxuat.DateTime.Date;
            rpt.Parameters["paraTongtien"].Value = txtTongtien.EditValue;
            if (Convert.ToInt32("0" + lookHinhthuc_Thanhtoan.EditValue) == 1)
            {                
                rpt.Parameters["paraSotien_Thanhtoan"].Value = txtSotien_Thanhtoan.EditValue;
                rpt.Parameters["paraSotien_Conlai"].Value = txtSotien_Conlai.EditValue;
            }
            else
            {
                rpt.xlbSotien_Thanhtoan.Visible = false;
                rpt.xlbSotien_Thanhtoan_Value.Visible = false;
                rpt.xlbSotien_Conlai.Visible = false;
                rpt.xlbSotien_Conlai_Value.Visible = false;
                rpt.xlb1.Visible = false;
                rpt.xlb2.Visible = false;
            }
                        
            frm.SetReport(rpt);
            frm.Show();
            frm.Activate();

            return true;
        }
        
        #endregion


        #region InsertObject, UpdateObject

        private bool InsertObject()
        {
            var save = false;
            phieuxuat.Id_Hinhthuc_Xuathang = lookHinhthuc_Thanhtoan.EditValue;
            phieuxuat.Id_Nha_Cungcap = lookNha_Cungcap.EditValue;
            phieuxuat.Tongtien = txtTongtien.EditValue;
            phieuxuat.Ngayxuat = dtNgayxuat.DateTime.Date;
            phieuxuat.Ghichu = txtGhichu.EditValue;
            if (Convert.ToDecimal("0" + lookHinhthuc_Thanhtoan.EditValue) == 1)
            {
                phieuxuat.Sotien_Thanhtoan = txtSotien_Thanhtoan.EditValue;
                phieuxuat.Sotien_Conlai = txtSotien_Conlai.EditValue;               
                if (Convert.ToDecimal("0" + txtSotien_Conlai.EditValue) > 0)
                    phieuxuat.Check_No = 1;
            }
            else
            {
                phieuxuat.Sotien_Thanhtoan = 0;
                phieuxuat.Sotien_Conlai = 0;
                phieuxuat.Check_No = 0;
            }

            identity = _objXuathang.Insert_Phieuxuat(phieuxuat).Rows[0]["value"];

            save = _objXuathang.Update_Phieuxuat_Chitiet_Collection(dtb_mathang, identity);

            return save;
        }

        private bool UpdateObject()
        {
            var save = false;
            phieuxuat.Id_Hinhthuc_Xuathang = lookHinhthuc_Thanhtoan.EditValue;
            phieuxuat.Id_Nha_Cungcap = lookNha_Cungcap.EditValue;
            phieuxuat.Tongtien = txtTongtien.EditValue;
            phieuxuat.Ngayxuat = dtNgayxuat.DateTime.Date;
            phieuxuat.Ghichu = txtGhichu.EditValue;
            phieuxuat.Id_Phieuxuat = gvPhieuxuat.GetFocusedRowCellValue("Id_Phieuxuat");
            if (Convert.ToDecimal("0" + lookHinhthuc_Thanhtoan.EditValue) == 1)
            {
                phieuxuat.Sotien_Thanhtoan = txtSotien_Thanhtoan.EditValue;
                phieuxuat.Sotien_Conlai = txtSotien_Conlai.EditValue;                
                if (Convert.ToDecimal("0" + txtSotien_Conlai.EditValue) > 0)
                    phieuxuat.Check_No = 1;
                else
                    phieuxuat.Check_No = 0;
            }
            else
            {
                phieuxuat.Sotien_Thanhtoan = 0;
                phieuxuat.Sotien_Conlai = 0;
                phieuxuat.Check_No = 0;
            }

            _objXuathang.Update_Phieuxuat(phieuxuat);
            identity = gvPhieuxuat.GetFocusedRowCellValue("Id_Phieuxuat");
            save = _objXuathang.Update_Phieuxuat_Chitiet_Collection(dtb_mathang, identity, "Update");

            return save;
        }

        #endregion


        #region Method

        private void lookNha_Cungcap_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                MasterForm.FrmNha_Cungcap _frmNha_Cungcap = new MasterForm.FrmNha_Cungcap();
                _frmNha_Cungcap.StartPosition = FormStartPosition.CenterScreen;
                _frmNha_Cungcap.ShowDialog();

                if (_frmNha_Cungcap.SelectedRow != null)
                {
                    if (dtb_nha_cungcap.Select(string.Format("Id_Nha_Cungcap = {0}", _frmNha_Cungcap.SelectedRow["Id_Nha_Cungcap"])).Length == 0)
                    {
                        dtb_nha_cungcap = _objNhaphang.GetAll_Nha_Cungcap();
                        lookNha_Cungcap.Properties.DataSource = dtb_nha_cungcap;
                    }
                    lookNha_Cungcap.EditValue = _frmNha_Cungcap.SelectedRow["Id_Nha_Cungcap"];
                }
            }
        }

        private void btnChon_Mathang_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.FormState != Windows.Forms.FormState.View)
                {
                    FrmMathang _frmMathang = new FrmMathang();
                    _frmMathang.StartPosition = FormStartPosition.CenterScreen;
                    _frmMathang.Is_Add = true;
                    _frmMathang.ShowDialog();

                    if (_frmMathang.SelectedRow != null)
                    {
                        foreach (DataRow row in _frmMathang.SelectedRow)
                        {
                            if (dtb_mathang.Select(string.Format("Id_Mathang = {0}", row["Id_Mathang"])).Length > 0)                            
                                continue;
                            
                            var rowAdd = dtb_mathang.NewRow();
                            foreach (DataColumn col in dtb_mathang.Columns)
                            {
                                try
                                {
                                    rowAdd[col.ColumnName] = row[col.ColumnName];
                                }
                                catch { continue; }
                            }
                            dtb_mathang.Rows.Add(rowAdd);
                        }
                        dgMathang.DataSource = dtb_mathang;                        
                    }
                }
            }
            catch (Exception ex)
            {
                Windows.Forms.Message.Show(ex.Message, ex.ToString());
            }
        }

        private void btnXoa_Mathang_Click(object sender, EventArgs e)
        {
            if (this.FormState != Windows.Forms.FormState.View)
            {
                try
                {
                    if (gvMathang.RowCount > 0)
                    {
                        var id_mathang = gvMathang.GetFocusedRowCellValue("Id_Mathang");
                        dtb_mathang.Rows.RemoveAt(gvMathang.FocusedRowHandle);                        
                    }
                }
                catch (Exception ex)
                {
                    Windows.Forms.Message.Show(ex.Message, ex.ToString());
                }
            }
        }


        #endregion

        private DataTable GetSchema_DataTable_Mathang()
        {
            DataTable dtb = new DataTable("dtb_mathang");
            dtb.Columns.Add("Id_Phieuxuat_Chitiet");
            dtb.Columns.Add("Id_Phieuxuat");
            dtb.Columns.Add("Id_Mathang");
            dtb.Columns.Add("Ten_Mathang");
            dtb.Columns.Add("Ten_Donvi_Tinh");
            dtb.Columns.Add("Soluong");
            dtb.Columns.Add("Dongia");
            dtb.Columns.Add("Thanhtien");
            return dtb;
        }

        private DataTable GetSchema_DataTable_Hinhthuc_Thanhtoan()
        {
            DataTable dtb = new DataTable("Tmp");
            dtb.Columns.Add("Id_Hinhthuc_Xuathang");
            dtb.Columns.Add("Ten_Hinhthuc_Xuathang");
            // Add data
            dtb.Rows.Add(1, "Xuất hàng bán sỉ");
            dtb.Rows.Add(2, "Xuất hàng bán lẻ");

            return dtb;
        }

        private void gvMathang_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (this.FormState != Windows.Forms.FormState.View)
            {
                int r = e.RowHandle;
                if (r < 0) return;
                var value = Convert.ToDecimal("0" + e.Value);

                if (e.Column.FieldName == "Soluong" && value != 0)
                {
                    if (value < 0)
                        gvMathang.SetFocusedRowCellValue("Soluong", 0);

                    var dongia = gvMathang.GetFocusedRowCellValue("Dongia");
                    var thanhtien = Convert.ToDecimal("0" + dongia) * value;
                    gvMathang.SetFocusedRowCellValue("Thanhtien", thanhtien);
                    if (thanhtien > 0)
                        txtTongtien.EditValue = Convert.ToDecimal("0" + txtTongtien.EditValue) + thanhtien;
                }

                if (e.Column.FieldName == "Dongia" && value != 0)
                {
                    if (value < 0)
                        gvMathang.SetFocusedRowCellValue("Dongia", 0);
                    var soluong = gvMathang.GetFocusedRowCellValue("Soluong");
                    var thanhtien = Convert.ToDecimal("0" + soluong) * value;
                    gvMathang.SetFocusedRowCellValue("Thanhtien", thanhtien);
                    if (thanhtien > 0)
                        txtTongtien.EditValue = Convert.ToDecimal("0" + txtTongtien.EditValue) + thanhtien;
                }
                

            }
            
        }

        private void gvMathang_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                if (e.Column.FieldName == "STT")
                    e.DisplayText = (Convert.ToInt64(e.RowHandle) + 1).ToString();
            }
        }

        private void calNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '-')
                e.Handled = true;
        }

        private void gvPhieunhap_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gvPhieuxuat.GetFocusedRowCellValue("Id_Phieuxuat") + "" != "" && this.FormState == Windows.Forms.FormState.View)
            {
                ClearDataBindings();
                DataBindingControl();
                dtb_mathang = _objXuathang.GetAll_Mathang_By_Id_Phieuxuat(gvPhieuxuat.GetFocusedRowCellValue("Id_Phieuxuat"));
                dgMathang.DataSource = dtb_mathang;
            }
            else
            {
                ClearDataBindings();
                ResetText();
                dgMathang.DataSource = null;
            }
        }

        private void gvPhieunhap_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                if (e.Column.FieldName == "STT")
                    e.DisplayText = (Convert.ToInt64(e.RowHandle) + 1).ToString();
            }
        }

        private void gvKho_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                if (e.Column.FieldName == "STT")
                    e.DisplayText = (Convert.ToInt64(e.RowHandle) + 1).ToString();
            }
        }

        private void lookHinhthuc_Thanhtoan_EditValueChanged(object sender, EventArgs e)
        {
            if (this.FormState != Windows.Forms.FormState.View)
            {
                txtSotien_Thanhtoan.Properties.ReadOnly = true;
                if (lookHinhthuc_Thanhtoan.EditValue + "" == "1")
                    txtSotien_Thanhtoan.Properties.ReadOnly = false;
                else
                    txtSotien_Thanhtoan.EditValue = null;
            }
        }

        private void txtSotien_Thanhtoan_EditValueChanged(object sender, EventArgs e)
        {
            if (this.FormState != Windows.Forms.FormState.View)
            {
                if (txtSotien_Thanhtoan.EditValue + "" != "" && txtTongtien.EditValue + "" != "")
                {
                    txtSotien_Conlai.EditValue = Convert.ToDecimal("0" + txtTongtien.EditValue) - Convert.ToDecimal("0" + txtSotien_Thanhtoan.EditValue);
                }
            }
        }

        private void txtTongtien_EditValueChanged(object sender, EventArgs e)
        {
            if (this.FormState != Windows.Forms.FormState.View)
            {
                if (txtSotien_Thanhtoan.EditValue + "" != "" && txtTongtien.EditValue + "" != "")
                {
                    txtSotien_Conlai.EditValue = Convert.ToDecimal("0" + txtTongtien.EditValue) - Convert.ToDecimal("0" + txtSotien_Thanhtoan.EditValue);
                }
            }
        }

        private void txtSotien_Thanhtoan_Properties_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '-')
                e.Handled = true;
        }

        private void gvPhieuxuat_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            GridView View = sender as GridView;
            if (e.RowHandle >= 0)
            {
                var check_no = View.GetRowCellDisplayText(e.RowHandle, View.Columns["Check_No"]);
                if (Convert.ToInt32("0" + check_no) == 1)
                {
                    e.Appearance.BackColor = Color.Khaki;
                    e.Appearance.BackColor2 = Color.Moccasin;                 
                }
            }
        }

        private void txtSotien_Thanhtoan_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '-')
                e.Handled = true;
        }

        
        















    }
}